from datetime import timedelta

from django.utils import timezone

from django.shortcuts import render
from django.http import HttpResponse
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from book import models,ser



# Create your views here.

class BookLookView(APIView):
    # 书籍查询
    def get(self, request):
        name = request.GET.get('name')
        if name:
            book = models.BookModel.objects.filter(title = name).first()
            sers = ser.BookSer(book)
            return Response(sers.data,status=status.HTTP_200_OK)
        else:
            book =  models.BookModel.objects.filter(status='1').all()
            sers = ser.BookSer(book,many=True)
            return Response(sers.data, status=status.HTTP_200_OK)

    # 书籍录入
    def post(self,request):
        data = request.data
        sers = ser.BookSer(data=data)
        if sers.is_valid():
            sers.save()
            return Response({'msg':'录入成功','code':status.HTTP_200_OK})
        return Response({'msg':sers.errors,'code':status.HTTP_400_BAD_REQUEST})

    # 书籍修改
    def put(self,request):
        data = request.data
        book = models.BookModel.objects.filter(id=data['id']).first()
        sers = ser.BookSer(book,data=data)
        if sers.is_valid():
            sers.save()
            return Response({'msg': '修改成功', 'code': status.HTTP_200_OK})
        return Response({'msg': sers.errors, 'code': status.HTTP_400_BAD_REQUEST})

    # 书籍删除
    def delete(self,request):
        id = request.GET.get('id')
        book = models.BookModel.objects.filter(id=id).first()
        book.delete()
        return Response({'msg': '删除成功', 'code': status.HTTP_200_OK})


# 借书
class BorrowBookView(APIView):
    def post(self,request):
        id = request.data.get('id')
        reader = request.data.get('reader')
        number = request.data.get('number')
        try:
            book_obj = models.BookModel.objects.get(id=id)
            if book_obj.status == '2':
                return Response({'msg':'书籍已借出','code':status.HTTP_400_BAD_REQUEST})
            # 如果库存充足
            if book_obj.number >= int(number):
                book_obj.number -= int(number)
                if book_obj.number == 0:
                    book_obj.status = '2'
                book_obj.save()
                # 还书时间
                return_date = timezone.now().date() + timedelta(days=30)
                models.BookRecordModel.objects.create(
                    book_id = id,
                    reader = reader,
                    return_date = return_date,
                    number = number
                )
                return Response({'msg':'借阅成功','code': status.HTTP_200_OK})

            #如果库存不足
            else:
                return Response({'msg':f'当前库存不足，剩余{book_obj.number}本，请重新输入借阅数量','code':status.HTTP_400_BAD_REQUEST})

        except models.BookModel.DoesNotExist:
            return Response({'msg':'书籍不存在','code':status.HTTP_400_BAD_REQUEST})

# 借阅记录
class BookHistoryView(APIView):
    def get(self,request):
        info = models.BookRecordModel.objects.filter(is_return=False).all()
        sers = ser.BookRecordSer(info,many=True)
        return Response(sers.data,status=status.HTTP_200_OK)

# 还书
class ReturnBookView(APIView):
    def post(self, request):
        id = request.data.get('id')
        reader = request.data.get('reader')
        print(id,reader)
        try:
            book_obj = models.BookRecordModel.objects.filter(book_id=id,reader=reader,is_return=False).first()
            book_obj.is_return = True
            book_obj.save()
            book = models.BookModel.objects.filter(id=id).first()
            book.number += book_obj.number
            book.save()
            return Response({'msg':'还书成功','code':status.HTTP_200_OK})
        except models.BookModel.DoesNotExist:
            return Response({'msg': '还书失败', 'code': status.HTTP_400_BAD_REQUEST})